<?php
/**
 * Class Minify_CSS_UriRewriter  
 * @package Minify
 */

/**
 * Rewrite root-relative to target directory file-relative URIs in CSS files
 *
 * @package Minify
 * @author Oleg Cherniy <oleg.cherniy@gmail.com>
 */
class Minify_CSS_UriRelative {
    
    /**
     * Rewrite root-relative to target directory file-relative URIs in CSS files
     * 
     * @param string $css
     * 
     * @param string $targetDir The target directory of CSS file.
     *
     * @return string
     */
    public static function rewrite($css, $targetDir) 
    {
        self::$_targetDirArray = split('/',
            preg_replace('@/$@','',$targetDir) # if the path has a slash at the end we remove it here
        );

        // rewrite
        $css = preg_replace_callback('/@import\\s+([\'"])(.*?)[\'"]/'
            ,array('Minify_CSS_UriRelative', self::$_callbackMethod), $css);
        $css = preg_replace_callback('/url\\(\\s*([^\\)\\s]+)\\s*\\)/'
            ,array('Minify_CSS_UriRelative', self::$_callbackMethod), $css);

        return $css;
    }
    
    /**
     * @var string directory of this stylesheet
     */
    protected static $_callbackMethod = '_uriCB';


    /**
     * @var array for make relative paths for target css file
     */
    protected static $_targetDirArray = array();

    private static function _uriCB($m)
    {
        $isImport = ($m[0][0] === '@');
        if ($isImport) {
            $quoteChar = $m[1];
            $uri = $m[2];
        } else {
            // is url()
            // $m[1] is either quoted or not
            $quoteChar = ($m[1][0] === "'" || $m[1][0] === '"')
                ? $m[1][0]
                : '';
            $uri = ($quoteChar === '')
                ? $m[1]
                : substr($m[1], 1, strlen($m[1]) - 2);
        }
        if ('/' === $uri[0]) {
            $uri = self::_makeRelativeUrl($uri);
        }
        if ($isImport) {
            return "@import {$quoteChar}{$uri}{$quoteChar}";
        } else {
            return "url({$quoteChar}{$uri}{$quoteChar})";
        }
    }

    protected static function _makeRelativeUrl($url)
    {
        foreach (self::$_targetDirArray as $dirPart) {
	    $url = preg_replace('@^'.$dirPart.'/@','',$url, -1, $changed);
	    if (!$changed) {
		$url = '../' . $url;
	    }
        }
	return $url;
    }

}
